package leetcode100;

import java.util.ArrayList;
import java.util.List;

public class lc035 {
    public static void main(String[] args) {
        int[] candidates = new int[] {2,3,6,7};
        int target = 7;
        List<List<Integer>> res=new lc035().combinationSum(candidates,target);
        System.out.println("res = " + res);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        List<List<Integer>> res = new ArrayList<>();

        backtrace(res,new ArrayList<>(),0,target,candidates);
        return res;
    }

    public void backtrace(List<List<Integer>> res,List<Integer> current,int index,int target,int[] candidates) {

        if (target==0) {
            res.add(current);
            System.out.println("res = " + res);
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (candidates[i]>target) {
                continue;
            }
            current.add(candidates[i]);
            System.out.println("current = " + current);
            target-=candidates[i];
            System.out.println("target = " + target);
            backtrace(res,current,i,target,candidates);
            target+=candidates[i];
            current.remove(current.size()-1);
        }
    }
}
